import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart' as path_helper;
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';

class DBHelper {
  static Database? _db;
  static const String dbName = 'transactions.db';
  static const int version = 1;

  static Future<Database> get database async {
    if (_db != null) return _db!;
    _db = await initDB();
    return _db!;
  }

  static Future<Database> initDB() async {
    final Directory documentsDirectory = await getApplicationDocumentsDirectory();
    final String dbPath = Platform.isWindows
        ? path_helper.join(documentsDirectory.path, 'databases', dbName)
        : path_helper.join(documentsDirectory.path, dbName);

    // 确保目录存在
    await Directory(path_helper.dirname(dbPath)).create(recursive: true);

    // Windows 平台使用 FFI
    if (Platform.isWindows) {
      return await databaseFactoryFfi.openDatabase(
        dbPath,
        options: OpenDatabaseOptions(
          version: version,
          onCreate: (Database db, int version) async {
            await db.execute('''
              CREATE TABLE transactions(
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                title TEXT NOT NULL,
                amount REAL NOT NULL,
                date TEXT NOT NULL,
                isExpense INTEGER NOT NULL,
                category TEXT NOT NULL,
                note TEXT,
                imagePath TEXT,
                isReimbursed INTEGER NOT NULL
              )
            ''');
          },
        ),
      );
    }

    // 其他平台使用默认实现
    return await openDatabase(
      dbPath,
      version: version,
      onCreate: (Database db, int version) async {
        await db.execute('''
          CREATE TABLE transactions(
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            amount REAL NOT NULL,
            date TEXT NOT NULL,
            isExpense INTEGER NOT NULL,
            category TEXT NOT NULL,
            note TEXT,
            imagePath TEXT,
            isReimbursed INTEGER NOT NULL
          )
        ''');
      },
    );
  }

  // 插入交易记录
  static Future<int> insertTransaction(Map<String, dynamic> transaction) async {
    final Database db = await database;
    return await db.insert(
      'transactions',
      {
        ...transaction,
        'isExpense': transaction['isExpense'] ? 1 : 0,
        'isReimbursed': transaction['isReimbursed'] ? 1 : 0,
      },
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  // 获取所有交易记录
  static Future<List<Map<String, dynamic>>> getTransactions() async {
    final Database db = await database;
    final List<Map<String, dynamic>> maps = await db.query('transactions');
    return maps.map((map) => {
      ...map,
      'isExpense': map['isExpense'] == 1,
      'isReimbursed': map['isReimbursed'] == 1,
    }).toList();
  }

  // 更新交易记录
  static Future<int> updateTransaction(Map<String, dynamic> transaction) async {
    final Database db = await database;
    return await db.update(
      'transactions',
      {
        ...transaction,
        'isExpense': transaction['isExpense'] ? 1 : 0,
        'isReimbursed': transaction['isReimbursed'] ? 1 : 0,
      },
      where: 'id = ?',
      whereArgs: [transaction['id']],
    );
  }

  // 删除交易记录
  static Future<int> deleteTransaction(int id) async {
    final Database db = await database;
    return await db.delete(
      'transactions',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  // 清空数据库
  static Future<void> clearDatabase() async {
    final Database db = await database;
    await db.delete('transactions');
  }
} 